﻿using Core;
using RI_Talisman;
using RimWorld;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Verse;
using Verse.AI;
using WhoXiuXian;

namespace RI_Talisman
{
    public sealed class BlindBoxOpeningManager : IExposable
    {
        private Dictionary<ThingDef, float> studyProgress = new Dictionary<ThingDef, float>();

        public void SetStudied(ThingDef thingDef, float amount)
        {
            if (!studyProgress.ContainsKey(thingDef))
            {
                studyProgress.Add(thingDef, 0f);
            }
            studyProgress[thingDef] += amount / (float)thingDef.GetCompProperties<CompProperties_BlindBoxUsing>().cost;
            studyProgress[thingDef] = Mathf.Clamp01(studyProgress[thingDef]);
        }

        public void ForceSetStudiedProgress(ThingDef thingDef, float progress)
        {
            if (!studyProgress.ContainsKey(thingDef))
            {
                studyProgress.Add(thingDef, 0f);
            }

            studyProgress[thingDef] = Mathf.Clamp01(progress);
        }

        public bool StudyComplete(ThingDef thingDef)
        {
            if (thingDef.GetCompProperties<RimWorld.CompProperties_Studiable>() == null)
            {
                return false;
            }

            if (studyProgress.ContainsKey(thingDef))
            {
                return studyProgress[thingDef] >= 1f;
            }

            return false;
        }

        public float GetStudyProgress(ThingDef thingDef)
        {
            if (!studyProgress.ContainsKey(thingDef))
            {
                return 0f;
            }

            return studyProgress[thingDef];
        }

        public IEnumerable<ResearchProjectDef> GetAllUnlockedResearch(ThingDef thingDef)
        {
            foreach (ResearchProjectDef allDef in DefDatabase<ResearchProjectDef>.AllDefs)
            {
                if (!allDef.requiredResearchFacilities.NullOrEmpty() && allDef.requiredResearchFacilities.Contains(thingDef))
                {
                    yield return allDef;
                }
            }
        }

        public void ResetAllProgress()
        {
            studyProgress.Clear();
        }

        public void ExposeData()
        {
            Scribe_Collections.Look(ref studyProgress, "studyProgress", LookMode.Def, LookMode.Value);
        }
    }
}